package com.hs.spp.ota;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import com.hs.color.lamp.BluetoothChatService;

import android.util.Log;

public class TransOverSpp {

	public Semaphore spp_recv_cnt       = new Semaphore(0);
	public Semaphore spp_recv_lock = new Semaphore(1);
	public BlockingQueue<Byte> spp_recv_data = new LinkedBlockingQueue<Byte>();
	
	private String tag = "TransOverSpp";
	public BluetoothChatService mChatService;
	public TransOverSpp(BluetoothChatService ChatService ){
		mChatService = ChatService;
	}
	public long hs_read(byte[] pData, int pos, int dataLen, int clrFlg)
	{
		boolean res = false;
		if(pData == null || pData.length < dataLen + pos)
			return -1;
		try {
			res = spp_recv_cnt.tryAcquire(dataLen, 5000, TimeUnit.MILLISECONDS);//TimeUnit.SECONDS
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   //  等待8000ms
		if (!res)
		{
			Log.i(tag, "receive timeout");
			return -1;
		}
		
		for (int i = 0; i < dataLen; i++)
		{
	
			try {
				spp_recv_lock.acquire(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(spp_recv_data.isEmpty())
				return -1;
			pData[i+pos] = spp_recv_data.poll();
			Log.i("SPPOTAFragment", "read:  "+pData[i+pos]+"");
			spp_recv_lock.release(1);
		}
		return 0;
	}
	
	
	
	public long hs_read(byte[] pData, int pos, int dataLen, int clrFlg, int tim_out_ms)
	{
		boolean res = false;
		if(pData == null || pData.length < dataLen + pos)
			return -1;
		try {
			res = spp_recv_cnt.tryAcquire(dataLen, tim_out_ms, TimeUnit.MILLISECONDS);//TimeUnit.SECONDS
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   //  等待8000ms
		if (!res)
		{
			Log.i(tag, "receive timeout");
			return -1;
		}
		
		for (int i = 0; i < dataLen; i++)
		{
	
			try {
				spp_recv_lock.acquire(1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(spp_recv_data.isEmpty())
				return -1;
			pData[i+pos] = spp_recv_data.poll();
			Log.i("SPPOTAFragment", "read:  "+pData[i+pos]+"");
			spp_recv_lock.release(1);
		}
		return 0;
	}
	
	
	public long hs_write(byte[] pData, int dataLen)
	{
		byte[] tmp = new byte[dataLen];
		System.arraycopy(pData, 0, tmp, 0, dataLen);
		if(mChatService != null){
			mChatService.write(tmp);
		}

		return 0;
	}
	
	public long hs_flush()
	{
		
		
		try {
			spp_recv_lock.acquire(1);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			spp_recv_cnt.acquire(spp_recv_data.size());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		spp_recv_data.clear();
		spp_recv_lock.release(1);
		return 0;
	}
}
